#ifndef DHD_CSERVER_THREAD_H
#define DHD_CSERVER_THREAD_H

#include <deque>

#include "c_connection.h"
#include "event_notifier.h"

namespace dhd
{
namespace client
{
   
   class ServerThread : public Refcounted, public IConnectionHandler
   {
       typedef std::deque< PInteraction > InteractionQueue;
       
       ServerCFG                      conf;
       boost::mutex                   svr_mutex;
       boost::asio::io_service        io_service;
       EventNotifier                  notifier;
       InteractionQueue               new_interactions;
       ReplyMap                       pending_replies;
       Connection                     conn;
       boost::thread                  svr_thread;
       uint16_t                       next_id;
       bool                           have_root;
       boost::asio::io_service::work *keep_running;

       // TODO: Return an error to all pending operations on this server
       virtual ~ServerThread();
       
       void run();
       
       void interaction_queued();
       
       void send_interaction( PInteraction pi );
       
       void got_server_root( const ToClient & reply );
       
     public:
       
       ServerThread( const ServerCFG & cfg );
       
       void on_zero_refcount() { delete this; }
       
       void queue_interaction( PInteraction & pi );
       
       // 'connected' means both having a network connection and having received the root
       // directory message
       bool is_connected() { return have_root; }
       
       
       void stop();
      
       //-----------------------------------------------------------------------
       // IConnectionHandler interface
       void connection_on_connect();
       
       // TODO: Iterate through all pending interactions and reply with errors
       //       to all that have 'reply_error_on_disconnect' flaged
       void connection_on_disconnect();
       
       void connection_on_reply( PInteraction pi );
       
       void connection_on_unsolicited( const ToClient & to_cli );
   };
   
   
   typedef boost::intrusive_ptr<ServerThread> PServerThread;
   
}//end namespace dhd::client
}//end namespace dhd

#endif

